package com.ikun.kunpicturebackend.aop;

import com.ikun.kunpicturebackend.annotation.AuthCheck;
import com.ikun.kunpicturebackend.domain.User;
import com.ikun.kunpicturebackend.exception.ErrorCode;
import com.ikun.kunpicturebackend.exception.ThrowUtils;
import com.ikun.kunpicturebackend.model.enums.UserRoleEnum;
import com.ikun.kunpicturebackend.service.UserService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * 权限校验切面类
 */
@Aspect
@Component
public class AuthInterceptor {

    @Resource
    private UserService userService;

    /**
     * 校验管理员权限
     * @param joinPoint
     * @param authCheck
     * @return
     * @throws Throwable
     */
    @Around("@annotation(authCheck)")
    public Object checkAuth(ProceedingJoinPoint joinPoint, AuthCheck authCheck) throws Throwable {
        //1. 从注解获取信息，判断是否拦截
        String mustRole = authCheck.mustRole();
        UserRoleEnum roleEnum = UserRoleEnum.getEnumByValue(mustRole);
        //1.1 无需权限，直接放行
        if (roleEnum == null) {
            joinPoint.proceed();
        }
        //1.2 判断注解中的权限信息是否是管理员
        ThrowUtils.throwIf(!UserRoleEnum.ADMIN.equals(roleEnum),
                ErrorCode.PARAMS_ERROR, "只对管理员权限做校验");

        //2. 获取请求信息
        RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
        HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();

        //3. 获取当前登录用户
        User loginUser = userService.getLoginUser(request);

        //4. 获取当前用户的权限
        UserRoleEnum role = UserRoleEnum.getEnumByValue(loginUser.getUserRole());
        ThrowUtils.throwIf(role == null, ErrorCode.NO_AUTH_ERROR);
        //4.1 判断是否是管理员权限
        ThrowUtils.throwIf(!UserRoleEnum.ADMIN.equals(role), ErrorCode.NO_AUTH_ERROR);
        return joinPoint.proceed();
    }
}
